package com.maltys.controller;

import com.maltys.redission.raw.ReentrantRedisLockV3;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author malty
 */
@RestController
@RequestMapping("/test")
public class ReentrantRedisLockV3TestController {

    private final AtomicInteger atomicInteger = new AtomicInteger(1);
    @Autowired
    ReentrantRedisLockV3 rawRedisLockV3;

    @RequestMapping("/v3/redis/lock")
    public void testRedisLockV3() {
        int finalI = 2;
        new Thread(() -> {
            try {
                String key = "t" + finalI;
                Long lock = rawRedisLockV3.tryLock("lock-v3", 10, key);
                if (lock == 1) {
                    System.out.println(key + " get lock");
                    System.out.println(key + " working...");
                } else {
                    System.out.println(key + " get lock failed -----------");
                    Thread.sleep(10);
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();
    }


    @RequestMapping("/v3/redis/unlock")
    public void testRedisReleaseLockV3() {
        atomicInteger.set(1);
        Runnable runnable = () -> {
            String name = "t" + atomicInteger.get();
            rawRedisLockV3.releaseLock("lock-v3", name);
        };
        new Thread(runnable).start();
    }
}
